<?php
/**
 * User: itimphp
 * Date: 6/6/12
 * Time: 12:36 AM
 */

class Form_Model
{
	/**
	 * @static
	 * @param $db_class Db_connect
	 * @param $post_data
	 * @return mixed
	 */
	public static function insertPostData($db_class, $post_data, $form_number = 1) {
		require_once 'includes/service_value.php';
//		$raw_posted = $post_data;
		$form_name_to_field_name = Service_Value::name_form_to_fields($form_number);

		// Modify some special fields before inserting to database
		if (isset($post_data['birth_date_year']) && isset($post_data['birth_date_month']) && isset($post_data['birth_date_day'])) {
			$datetime = intval($post_data['birth_date_year']) . '/' . intval($post_data['birth_date_month'])
				. '/' . ($post_data['birth_date_day']);

			$post_data['birth_date'] = date('Y-m-d H:i:s', strtotime($datetime));
			$form_name_to_field_name['birth_date'] = 'birthday';
		}
		// Time at current home
		if (isset($post_data['address_length_year']) && isset($post_data['address_length_month'])) {
			$post_data['address_length'] = floatval($post_data['address_length_year'] . '.' . str_pad($post_data['address_length_month'], 2, '0', STR_PAD_LEFT));
			$form_name_to_field_name['address_length'] = 'timeAtHome';
		}
		// Next Paydate
		if (isset($post_data['next_pay_date'])) {
			$post_data['next_pay_date'] = date('Y-m-d H:i:s', strtotime($post_data['next_pay_date']));
		}
		// Paydate After Next
		if (isset($post_data['pay_date_after'])) {
			$post_data['pay_date_after'] = date('Y-m-d H:i:s', strtotime($post_data['pay_date_after']));
		}
		// Time Employed
		if (isset($post_data['employed_time_year']) && isset($post_data['employed_time_month'])) {
			$post_data['employed_time'] = floatval($post_data['employed_time_year'] . '.' . str_pad($post_data['employed_time_month'], 2, '0', STR_PAD_LEFT));
			$form_name_to_field_name['employed_time'] = 'employedTime';
		}

		foreach ($post_data as $field_name => $value) {
			unset($post_data[$field_name]);
			if (array_key_exists($field_name, $form_name_to_field_name)) {
				$post_data[$form_name_to_field_name[$field_name]] = $value;
			}
		}

		return($db_class->insert_record('loans', $post_data));
	}
}